package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hhs.storage.bean.InputParam;
import com.hhs.storage.bean.ResponseInfo;
import com.hhs.storage.bean.UserFollowGroup;
import com.hhs.storage.bean.UserFollowList;
import com.hhs.storage.dao.UserFollowGroupDao;
import com.hhs.storage.service.UserFollowGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.service.UserFollowListService;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-04-19
 */
@Service
@Transactional
public class UserFollowGroupServiceImpl extends ServiceImpl<UserFollowGroupDao, UserFollowGroup> implements UserFollowGroupService {
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserFollowListService userFollowListService;

    /**
     * 查询用户所有分组
     * @return
     */
    @Override
    public Map getAll(InputParam inputParam) {
        QueryWrapper<UserFollowGroup> qw=new QueryWrapper<>();
        if (StringUtils.isNotEmpty(inputParam.getName())){
            qw.like("name",inputParam.getName());
        }
        qw.eq("user_id", SysUtil.getLoginUserId(request));
        qw.orderByDesc("create_time");
        return ResponseInfo.success(this.list(qw));
    }

    /**
     * 新增或编辑分组
     * @param userFollowGroup
     * @return
     */
    @Override
    public Map edit(UserFollowGroup userFollowGroup,String followUserIds) {
        if (StringUtils.isEmpty(userFollowGroup.getName())){
            return ResponseInfo.error("分组名不可为空");
        }
        String userId=SysUtil.getLoginUserId(request);//当前用户id
        if (StringUtils.isEmpty(userFollowGroup.getId())){
            QueryWrapper<UserFollowGroup> qw=new QueryWrapper<>();
            qw.eq("name",userFollowGroup.getName());
            qw.eq("user_id",userId);
            if (this.count(qw)>0){
                return ResponseInfo.error("分组名已存在");
            }
            //新增
            userFollowGroup.setId(SysUtil.UUID());
            userFollowGroup.setCreateTime(LocalDateTime.now());
            userFollowGroup.setUserId(SysUtil.getLoginUserId(request));
            this.save(userFollowGroup);
            //添加关注的人
            addGroupFollowUsers(userFollowGroup, followUserIds, userId);
            return ResponseInfo.success("新增成功");

        }else {
            //编辑
            QueryWrapper<UserFollowGroup> qw=new QueryWrapper<>();
            qw.eq("name",userFollowGroup.getName());
            qw.eq("user_id",userId);
            qw.ne("id",userFollowGroup.getId());
            if (this.count(qw)>0){
                return ResponseInfo.error("分组名已存在");
            }
            UpdateWrapper<UserFollowGroup> uw=new UpdateWrapper<>();
            uw.set("name",userFollowGroup.getName());
            uw.eq("id",userFollowGroup.getId());
            this.update(uw);
            //删除原有的数据
            QueryWrapper queryWrapper=new QueryWrapper<UserFollowList>();
            queryWrapper.eq("user_id",userId);
            queryWrapper.eq("group_id",userFollowGroup.getId());
            userFollowListService.remove(queryWrapper);
            //添加关注的人
            addGroupFollowUsers(userFollowGroup, followUserIds, userId);
            return ResponseInfo.success("编辑成功");
        }

    }

    /**
     * 添加分组中关注的人
     * @param userFollowGroup
     * @param followUserIds
     * @param userId
     */
    public void addGroupFollowUsers(UserFollowGroup userFollowGroup, String followUserIds, String userId) {
        if (StringUtils.isNotEmpty(followUserIds)){
            String[] followUserIds_arr=followUserIds.split(",");
            for (int i = 0; i <followUserIds_arr.length ; i++) {
                UserFollowList temp=new UserFollowList();
                temp.setId(SysUtil.UUID());
                temp.setGroupId(userFollowGroup.getId());
                temp.setUserId(userId);
                temp.setFollowUserId(followUserIds_arr[i]);
                temp.setCreateTime(LocalDateTime.now());
                userFollowListService.save(temp);
            }
        }
    }

    /**
     * 删除分组
     * @param id
     * @return
     */
    @Override
    public Map delete(String id) {
        this.removeById(id);
        return ResponseInfo.success();
    }

    @Override
    public Map getAllAndMembers(InputParam inputParam) {
        QueryWrapper<UserFollowGroup> qw=new QueryWrapper<>();
        qw.eq("user_id", SysUtil.getLoginUserId(request));
        qw.orderByDesc("create_time");
        List<UserFollowGroup> list = this.list(qw);
//        Set<String> userSet = new HashSet<>();
        List list1 = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            UserFollowGroup userFollowGroup = list.get(i);
            Map map = new HashMap();
            map.put("id",userFollowGroup.getId());
            map.put("userId",userFollowGroup.getUserId());
            map.put("name",userFollowGroup.getName());
            map.put("createTime",userFollowGroup.getCreateTime());
            QueryWrapper<UserFollowList> qw2=new QueryWrapper<>();
            qw2.eq("user_id",SysUtil.getLoginUserId(request));
            qw2.eq("group_id",userFollowGroup.getId());
            List<UserFollowList> userList=userFollowListService.list(qw2);
            List myList = new ArrayList();
            for (UserFollowList userFollow  : userList) {
                myList.add(userFollow.getFollowUserId());
            }
            map.put("idList",myList);
            list1.add(map);
        }
        HashMap map = new HashMap();
        map.put("groups",list1);
//        map.put("members",String.join(",",userSet));
        return ResponseInfo.success(map);
    }
}
